<template>
  <div class="mainos">
    <div class="main_spac1 paddingBottom5">
      <div class="main_white padding10">
        <div class="main_crumbs boxdq">
          <div class="main_crumbs_l">
            <a href="javascript:;" @click="$router.back(-1)">
              <i class="el-icon-arrow-down"></i>返回
            </a>
            <em>|</em>
            <span>模板设置</span>
          </div>
          <div class="main_crumbs_rt box">
            <el-button @click="addOldTempalte" v-if="!companyInfo.send_order_template_type">
              新增模板
              <el-tooltip class="item" effect="dark" placement="bottom">
                <div slot="content">
                  注释：新增/编辑旧版模版保存后，打印时，系统会默认使用旧版模版进行打印；<br>
                  如旧版模版，新版模版都有，系统将按最新保存过的模版进行打印。
                </div>
                <svg-icon class="navbar_svg new_navbar_svg" iconClass="summary_question"> </svg-icon>
              </el-tooltip>
            </el-button>
            <el-button @click="addNewTempalte" style="position: relative;" v-else>
              新增模板
              <el-tooltip class="item" effect="dark" placement="bottom">
                <div slot="content">
                  注释：新增/编辑新版模版保存后，打印时，系统会默认使用新版模版进行打印；<br>
                  如旧版模版，新版模版都有，系统将按最新保存过的模版进行打印
                </div>
                <svg-icon class="navbar_svg new_navbar_svg" iconClass="summary_question"> </svg-icon>
              </el-tooltip>
              <div class="xin">新</div>
            </el-button>
          </div>
        </div>
        <div class="main-controls-wrap flex-middle remindBox">
          <svg-icon class="icon" iconClass="remind"></svg-icon>
          <span class="text">您正在使用{{ templateVersionText(false) }}打印模板，您可以切换至{{ templateVersionText(true) }}。</span>
          <el-button class="mainor_tea" :loading="mainLoading" @click="changeTemplateType">切换至{{ templateVersionText(true) }}</el-button>
        </div>
        <div v-loading="mainLoading">
          <div class="main_table" style="min-height: 550px">
            <el-table
              ref="multipleTable"
              v-loading="listLoading"
              :data="list"
              element-loading-text="加载中"
              fit
              border
              highlight-current-row
              row-key="uid"
              :header-cell-class-name="this.$verticaline"
              :header-cell-style="tableHeightStyle"
              @header-dragend="changeTableWidth"
            >
              <el-table-column label="顶部标题" prop="name" :width="tableWidth[hash+'name']" />
              <el-table-column
                label="用户"
                prop="member_info.code"
                align="center"
                :width="tableWidth[hash+'member_info.code']"
              >
                <template slot-scope="scope">
                  <div v-if="scope.row.default == 1">
                    <el-tag type="danger" size="mini">默认</el-tag>
                  </div>
                  <div v-else class="tag_box">
                    <el-tag
                      v-for="item in scope.row.new_member_ids"
                      :key="item"
                      type="success"
                      size="mini"
                    >
                      {{ (member[item] || {}).nickname }}
                    </el-tag>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="创建时间"
                :width="tableWidth[hash+'created_at'] || 200"
                prop="created_at"
                align="center"
                :show-overflow-tooltip="true"
              >
                <template slot-scope="scope">
                  {{ parseTime(scope.row.created_at) }}
                </template>
              </el-table-column>
              <el-table-column
                label="更新时间"
                :width="tableWidth[hash+'updated_at'] || 200"
                prop="updated_at"
                align="center"
                :show-overflow-tooltip="true"
              >
                <template slot-scope="scope">
                  {{ parseTime(scope.row.updated_at) }}
                </template>
              </el-table-column>
              <el-table-column 
                label="备注" 
                :show-overflow-tooltip="true"
                :width="tableWidth[hash+'remark']" 
                prop="remark"
              />
              <el-table-column 
                label="操作" 
                fixed="right"
                prop="operate"
                :width="tableWidth[hash+'operate'] || 200"
              >
                <template slot-scope="scope">
                  <el-button
                    type="primary"
                    v-repeatClick
                    @click="handleEdit(scope)"
                    >编辑</el-button
                  >
                  <el-button
                    type="info"
                    v-repeatClick
                    @click="handleReset(scope)"
                    >重置</el-button
                  >
                  <el-dropdown>
                    <el-button type="primary" class="el-dropdown-link mg-l-5">更多</el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item>
                        <div @click="copyTemplate(scope.row)">复制</div>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <div @click="handleDelete(scope)" v-repeatClick v-show="scope.row.default != 1">删除</div>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="main_page boxdq">
            <div></div>
            <!-- 分页 -->
            <div class="main_page_r">
              <MainPagination
                :current-page="current.page"
                :page-sizes="[20, 30, 50, 100]"
                :page-size="limit"
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalCount"
                @size-change="changeLimit"
                @current-change="changePage"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getTemplateList,
  reset_template,
  delTemplate,
} from "@/api/global/globalPrint";
import { setting_company } from "@/api/currency";
import { mapGetters } from "vuex";
import { mixins } from '@/mixins/index.js';
import { packApi } from "@/utils/public";
import { parseTime } from "@/utils/index";
export default {
  mixins: [mixins],
  inject: ["broadcast"],
  computed: {
    ...mapGetters(["companyInfo"]),
    templateVersionText({ companyInfo }) {
      return (type)=> {
        // 使用异或运算符 (^) 对 'type' 和 'companyInfo.send_order_template_type' 进行运算
        // 如果 'type' 和 'companyInfo.send_order_template_type' 相同，结果为 0
        // 如果 'type' 和 'companyInfo.send_order_template_type' 不同，结果为 1
        return (type ^ companyInfo.send_order_template_type) ? "新版" : "旧版";
      }
    },
  },
  data() {
    return {
      parseTime,
      id: this.$route.params.id,
      // 分页
      current: {
        page: 1,
        per_page: 20,
      },
      limit: 20,
      totalCount: 1,
      listLoading: false,
      mainLoading: false,
      // 列表数据
      list: [],
      form: {
        tem_id: "",
      },
      member: {},
      // 弹窗
      lineVisible: false,
    };
  },
  mounted(){
    let yindaoList = [
      {
        element: document.querySelector("#attachments"), // 定位到相应的元素位置，如果不设置element，则默认展示在屏幕中央
        title: "新增模版", // 标题
        intro: `<img src="https://copartner.oss-cn-beijing.aliyuncs.com/logo/2312/20/MNfkXrCnDQDvnMi5st6hJaoi5KF7ONCVcSon3ILL.png"/>`, // 内容
      },
      {
        element: document.querySelector("#telephone"),
        title: "表内设置", // 标题
        intro: `<img src="https://copartner.oss-cn-beijing.aliyuncs.com/logo/2312/20/Fr2yEhnHLiczbl0cSqBgGQiCxnl4cnTXALV5ZmBs.png"/>`, // 内容
      },
      {
        element: document.querySelector("#telephone"),
        title: "删除修改位置", // 标题
        intro: `<img src="https://copartner.oss-cn-beijing.aliyuncs.com/logo/2312/20/aLk20mIGgMK03kpn5xhIcTRVdo2VfcERlejPGV28.png"/>`, // 内容
      },
      {
        element: document.querySelector("#telephone"),
        title: "修改内容和添加自定义", // 标题
        intro: `<img src="https://copartner.oss-cn-beijing.aliyuncs.com/logo/2312/20/FysdRSsdkCDdhi3hA91FORZndR1dEZwEA3WcKJ7j.png"/>`, // 内容
      },
      {
        element: document.querySelector("#telephone"),
        title: "表格设置", // 标题
        intro: `<img src="https://copartner.oss-cn-beijing.aliyuncs.com/logo/2312/20/ief92jSXyPSJO5kNmR7vw0laESlPb9DAywoKAJIj.png"/>`, // 内容
      },
      {
        element: document.querySelector("#telephone"),
        title: "打印预览", // 标题
        intro: `<img src="https://copartner.oss-cn-beijing.aliyuncs.com/logo/2312/20/3byTcASxpN0kIfJtLtIArCYC2FMZQ1rxsSE3dbe2.png"/>`, // 内容
      },
    ];
    // 获取缓存中是否存在引导列表状态
    let state = localStorage.getItem("yindaoPrint");
    if (!state) {
      this.$intro()
        .setOptions({
          steps: yindaoList, //上面声明的数组
          nextLabel: "下一步", // 下一个的按钮文字
          prevLabel: "上一步", // 上一个按钮文字
          skipLabel: "跳过", // 跳过指引的按钮文字
          doneLabel: "完成", // 完成按钮的文字
          hidePrev: false, // 是否在第一步中隐藏“上一步”按钮;不隐藏，将呈现为一个禁用的按钮
          hideNext: false, // 是否在最后一步中隐藏“下一步”按钮（同时会隐藏完成按钮);不隐藏，将呈现为一个禁用的按钮
          exitOnEsc: false, // 点击键盘的ESC按钮是否退出指引
          exitOnOverlayClick: false, // 点击遮罩层时是否退出介绍
          showStepNumbers: true, // 是否显示步骤编号
          disableInteraction: true, // 是否禁用高亮显示框内元素的交互
          showBullets: true, // 是否显示面板的指示点
          overlayOpacity: 0.7, // 遮罩层的透明度 0-1之间
          helperElementPadding: 10, // 选中的指引元素周围的填充距离
          showProgress: false, //进度条
        })
        // 点击跳过按钮后执行的事件
        .onexit(() => {
          localStorage.setItem("yindaoPrint", "true");
        })
        // 确认完毕之后执行的事件
        .onbeforeexit(() => {
          localStorage.setItem("yindaoPrint", "true");
        })
        // .start();
    }
    window['getData'] = () => {
      this.getTemplateList()
    }
    this.broadcast.onmessage = ({ data }) => {
      if(data.path==="/delivery/index") this.getTemplateList();
    }
  },
  methods: {
    //  复制订单
    copyTemplate({ id, is_new }) {
      let tem_id = this.form.tem_id;
      let name = is_new ? "delivery" : "addOrderPrint";
      let routeData = this.$router.resolve({
        name,
        query: {
          id: id,
          change_user: 1,
          tem_id: tem_id,
          copy: true,
        },
      });
      window.open(routeData.href, "_blank");
    },
    // 分页
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      this.getTemplateList();
    },
    changePage(page) {
      this.current.page = page;
      this.getTemplateList();
    },
    // 切换模版
    changeTemplateType() {
      this.mainLoading = true;
      let send_order_template_type = this.companyInfo.send_order_template_type ? 0 : 1;
      setting_company(packApi({ send_order_template_type})).then(res=> {
        if(res.errcode == 0) {
          this.$store.commit("user/SET_COMINFO", { ...this.companyInfo, send_order_template_type });
          this.getTemplateList();
        } else {
          this.$message.error("操作失败");
          this.mainLoading = false;
        }
      });
    },
    getTemplateList() {
      this.mainLoading = true;
      let data = packApi({
        ...this.form,
        ...this.current,
        is_new: this.companyInfo.send_order_template_type
      });
      getTemplateList(data).then((res) => {
        this.mainLoading = false;
        if (res.errcode == 0) {
          res.list.map((e) => {
            e.name = "";
            e.new_member_ids = [];
            if (e.member_ids) {
              e.new_member_ids = e.member_ids.split(",");
            }
            try {
              let str = JSON.parse(e.print_settings);
              e.name = str.page.headerTitle;
            } catch (error) {
              console.log("错误", error);
            }
          });
          this.member = res.member;
          this.list = res.list;
          this.totalCount = res.count;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 编辑
    handleEdit({ row }) {
      let { id, tem_id } = row;
      let query = { id, tem_id };
      let default_tem = row.default;
      if (!default_tem) {
        query.change_user = 1;
      }
      let name = row.is_new ? "delivery" : "orderprint";
      let routeData = this.$router.resolve({
        name,
        query: query,
      });
      window.open(routeData.href, "_blank");
    },
    // 重置
    handleReset({ row }) {
      let id = row.id;
      let is_new = row.is_new ? 1 : 0;
      let data = packApi({ id, is_new });
      reset_template(data).then((res) => {
        if (res.errcode == 0) {
          this.getTemplateList();
          this.$message.success("重置成功");
        } else {
          this.$message.error("操作失败");
        }
      });
    },
    // 删除
    handleDelete(scope) {
      let row = scope.row;
      let id = row.id;
      if (row.default == 1) {
        this.$message.error("默认模板不能删除!");
        return;
      }
      let data = packApi({ id });
      delTemplate(data).then((res) => {
        if (res.errcode == 0) {
          this.$message.success("删除成功");
          this.getTemplateList();
        } else {
          this.$message.error("删除成功");
        }
      });
    },
    // 新增模板
    addOldTempalte() {
      let tem_id = this.form.tem_id;
      let routeData = this.$router.resolve({
        name: "addOrderPrint",
        query: {
          change_user: 1,
          tem_id: tem_id,
        },
      });
      window.open(routeData.href, "_blank");
    },
    // 新版模板
    addNewTempalte() {
      let tem_id = this.form.tem_id;
      let routeData = this.$router.resolve({
        name: "delivery",
        query: {
          change_user: 1,
          tem_id: tem_id,
        },
      });
      window.open(routeData.href, "_blank");
    },
  },
  created() {
    if (this.$route.params.id) {
      this.form.tem_id = this.$route.params.id;
    }
    this.getTemplateList();
  },
};
</script>

<style lang="scss" scoped>
.mg-l-5 {
  margin-left: 5px;
}
/deep/.main_table .el-table--small td .cell {
  height: auto;
  .tag_box {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: center;
    .el-tag {
      margin: 3px;
    }
  }
}
/deep/.el-button--danger:focus,
.el-button--danger:hover {
  background: #f78989;
  border-color: #f56c6c;
  color: #fff;
}
/deep/.el-button--primary:focus,
.el-button--primary:hover {
  background: #fff;
  border-color: #03a98e;
  color: #03a98e;
}
/deep/.el-button--info:focus,
.el-button--info:hover {
  background: #ffffff;
  border-color: #ebebeb;
  color: #333333;
}
/deep/.el-tabs__item.is-active{
  color:#03a98e !important;
}
/deep/.el-tabs__item:hover{
  color:#03a98e !important;
}
/deep/.el-tabs__active-bar{
  background-color: #03a98e !important;
}
.el-tabs{
  margin-top: 10px;
}
.xin{
  font-size: 10px;
  position: absolute;
  top: -8px;
  right: -8px;
  background-color: red;
  color: white;
  padding: 3px;
  border-radius: 20px;
}
/deep/.el-button--info {
  color: #fff;
  &:hover {
    background: rgba(3,169,142, .7);
    border-color: rgba(3,169,142, .7);
    color: #fff;
  }
}
.remindBox {
  padding: 10px;
  margin: 0 0 10px 0;
  border-bottom: 1px solid #E4E7ED;
  justify-content: flex-start;
  .icon {
    font-size: 14.55px;
  }
  .text {
    margin: 0 8px;
    font-size: 14px;
    color: #666666;
  }
}
.new_navbar_svg {
  vertical-align: middle;
}
</style>
